package com.wanxi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.wanxi.dao.CompanyDao;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.Company;
import com.wanxi.service.CompanyService;
import com.wanxi.util.JsonCopy;
import com.wanxi.vo.CompanyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Chengbo Zhang
 */
@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {
    @Autowired
    CompanyDao companyDao;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public ResultDTO findCompany() {
        String redisCompany = stringRedisTemplate.opsForValue().get("company");
//        判断redis中是否有数据
        if(redisCompany!=null){
//            返回redis中的数据,通过fastJson转换
            Company company= JSON.parseObject(redisCompany, new TypeReference<Company>() {});
            return ResultDTO.getDTO(1,company);
        }
//        没有则从数据库中找数据
        Company c =companyDao.selectById(1L);
        if(c!=null){
//            将查到的数据放入redis
            stringRedisTemplate.opsForValue().set("company", JSON.toJSONString(c),600, TimeUnit.SECONDS);
            return ResultDTO.getDTO(1,c);
        }
        return ResultDTO.builder().count(0).msg("error").code(1).build();
    }

    @Override
    public ResultDTO update(CompanyVO companyVO) {
        Company company= JsonCopy.copy(companyVO, Company.class);
        company.setId(1L);
        company.setUpdateTime(new Date());
        int i=companyDao.updateById(company);
        if(i==1){
            stringRedisTemplate.delete("company");
            return ResultDTO.getDTO(i,companyVO);
        }
        return ResultDTO.getDTO(0,companyVO);
    }
}
